#include <iostream>
#include <unordered_map>
#include <utility>
#include<thread>
#include "Serial.h"
#include "SQL_Conn.h"
#include "RFID.h"
#include "defines.h"
using namespace std;

vector<unsigned char> send_readCommand =	{ 0xBB, 0x17, 0x02, 0x00, 0x00, 0x19, 0x0D, 0x0A };		//多次查询
vector<unsigned char> send_readEND =		{ 0xBB, 0x18, 0x00, 0x18, 0x0D, 0x0A };					//关闭多次查询


void handle_RFID_Thread(vector<RFID::RFID_Struct> rfid_arr);

int main()
{
	Serial* serial = new Serial();
	bool isOpen = false;
	isOpen = serial->open_serial(RFIDCOM, CBR_115200);
	if (!isOpen) {
		return 0;
	}
	cout << rfid_com_1 << "  打开成功" << endl;
	RFID rfid_data;
	rfid_data.setEPCTimeMap();

	serial->send_RFID_command(send_readCommand);

	while (true) {
		//获取串口数据
		auto receive_data = serial->read_RFID_data();
		//解析数据
		rfid_data.get_RFID_Tag(receive_data);
		//生命周期TTL+1
		for (auto it = rfid_data.rfid_data_map_vec.begin(); it != rfid_data.rfid_data_map_vec.end();) {
			string currTime = getCurrentTime();
			string epc_endTime = it->second.back().Time;
			string timeGap = calcuTimeGap(epc_endTime, currTime);
			//最后一次读到的时间离现在大于十秒，则判定已离开
			if (timeGap >= OUT_NESTLE) {
				thread handle_rfid_thread(handle_RFID_Thread, it->second);
				handle_rfid_thread.join();
				it = rfid_data.rfid_data_map_vec.erase(it); // erase 返回下一个有效的迭代器  
			}
			else {
				++it; // 否则，递增迭代器以继续遍历  
			}
		}
		//判断进出

	}
	serial->send_RFID_command(send_readEND);
	serial->closeHandle();
	return 0;
}

void handle_RFID_Thread(vector<RFID::RFID_Struct> rfid_arr) {

	RFID::isEnterOrExit(rfid_arr);
}